#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

void * start_routine(void * arg);
char message[] = "Hello World";

int thread_finished = 0;

int main()
{
    int res;
    pthread_t a_thread;
//    void * thread_result;

    pthread_attr_t thread_attr;
    res = pthread_attr_init(&thread_attr);
    if (res != 0){
        perror("pthread_attr_init failure");
        exit(EXIT_FAILURE);
    }
    res = pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED);
    if (res != 0){
        perror("pthread_attr_setdetachstate failure");
        exit(EXIT_FAILURE);
    }

//    res = pthread_create(&a_thread,NULL,start_routine,(void*) message);
    res = pthread_create(&a_thread,&thread_attr,start_routine,(void *)message);
    if (res != 0){
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }
    (void) pthread_attr_destroy(&thread_attr);
 /*   while(!thread_finished){
        printf("Waiting for thread to say it's finished...\n");
        sleep(1);
    }
*/
//    res = pthread_attr_setdetachstatead_join(a_thread,&thread_result);//用于等待子线程的结束，arg1：指定子线程的标识符，arg2：子线程的返回值。即pthread_exit的参数
    printf("Message is now [%s]\n",message);
    exit(EXIT_SUCCESS);
}

void * start_routine(void * arg)
{
    printf("child Thread is running ,Argument was [%s]\n",(char*)arg);
    sleep(4);
//    strcpy(message,"Bye!");

    printf("Send thread settting finished flag,and exiting now\n");
    
    thread_finished = 1;
    pthread_exit("Cpu time");
}
